<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/12/3
 * Time: 17:37
 */

namespace App\Extend\SysExtend\Command;


use EasySwoole\EasySwoole\Command\CommandInterface;

/**
 * 生成队列消费者类
 * Class QueueConsumer
 * @package App\Extend\SysExtend\Command
 */
class QueueConsumer implements CommandInterface
{
    public function commandName(): string
    {
        // TODO: Implement commandName() method.
        return 'make:consumer';
    }

    public function exec(array $args): ?string
    {
        // 生成控制器，控制器目录App/HttpController, 参数就是控制器的路径和名称
        $base_path = EASYSWOOLE_ROOT . '/App/Common/Queue';
        if(empty($args[0])) {
            return '<error> please input consumer file name';
        }
        // 判断文件是否存在
        if(is_file($base_path . $args[0] . '.php')) {
            return '<error> consumer already existed!';
        }

        // 分开路径和控制器名
        $c_arr = explode('/', $args[0]);

        // 首字母大写
        foreach ($c_arr as &$v) {
            $v = ucfirst($v);
        }

        if(count($c_arr) == 1) {
            $dir = '';
            $file = $c_arr[0];
        }else{
            $file = array_pop($c_arr);
            $dir = implode('/',$c_arr);
        }

        // 创建文件夹
        if(!is_dir($base_path . $dir)) {
            mkdir($base_path . $dir, 0777, true);
        }

        // 组装命名空间
        $namespace = $dir ? '\\' . str_replace('/','\\', $dir) : '';
        // 生成队列名 大驼峰转下划线
        $queue = ltrim(strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $file)),'_');

        // 写入文件
        $content = <<<EOF
<?php

namespace App\Common\Queue{%namespace%};

use App\Extend\SysExtend\Helper;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Queue\Job;

/**
 * 
 * Class {%class_name%}
 * @package App\Common\Queue
 */
class {%class_name%} extends AbstractProcess
{
    /**
     * 执行逻辑
     * @param \$arg
     */
    protected function run(\$arg)
    {
        go(function () {
            if(!Helper::Queue()->getPid('{%queue%}')) {
                // 将进程ID存入缓存
                Helper::Queue()->setPid('{%queue%}', \$this->getPid());
            }
            Helper::Queue()->getQueue('{%queue%}')->consumer()->listen(function (Job \$job){
                \$data = \$job->toArray();
                // TODO 
            });
        });
    }
    
    /**
     * 异常回调
     * @param \Throwable \$throwable
     * @param mixed ...\$args
     * @throws \Throwable
     */
    protected function onException(\Throwable \$throwable, ...\$args)
    {
        parent::onException(\$throwable,...\$args);
    }
}
EOF;
        $content = str_replace('{%namespace%}', $namespace, $content);
        $content = str_replace('{%class_name%}', $file, $content);
        $content = str_replace('{%queue%}', $queue, $content);
        file_put_contents($base_path . $dir . '/' . $file . '.php', $content);
        return '<success> create consumer success!';
    }

    public function help(array $args): ?string
    {
        // TODO: Implement help() method.
        return 'auto create consumer';
    }
}